<template>
    <div class="Department ">
        <div class="DepartmentBtn">
            <el-button :disabled="isDisabled" type="primary" @click="add">新增</el-button>
        </div>
       <div class="DepartmentWrap clearfix">
            <!-- 左侧树 -->
            <div class="leftTree">
                <span :class="sanjiao"></span>
                <el-tree :data="dataTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
            </div>
            <!-- 右侧内容 -->
            <div class="rightContent" v-show="isFirst">
                <!-- <TopFilter
                :list="formList"
                :cols="7"
                :isSubmitBtn="false"
                ></TopFilter> -->
                <FormPanel
                ref="formPanel"
                :cols="2"
                :list="formList"
                formType="edit"
                :isSubmitBtn="false"
                />
                <!-- :onCellChange="onCellChange" -->
                <FilterTable
                v-if="isShowFilterTable"
                ref="table"
                :columns="columns"
                :dataSource="dataSource"
                :isSelectColumn="false"
                :height="TabHeight"
                :onColumnsChange="columns => this.columns = columns"
                >
                <!-- <FilterTable
                v-if="isShowFilterTable"
                ref="table"
                :columns="columns"
                :fetchapi="fetchApi"
                :params="params"
                :datakey="'listOBSVO'"
                :isSelectColumn='false'
                :onColumnsChange="columns => this.columns = columns"
                >-->
                 <template slot="controls" slot-scope="props">
                    <el-button size="small" v-show="isShowadd" type="primary"  @click="addHandle(props)">新增</el-button>
                </template>
                </FilterTable> 

                <div class="submit">
                    <el-button type="primary" v-show="isShowSubmit" :disabled="isSaveDisabled" @click="submit">保存</el-button>
                </div>
            </div>
       </div>
       <BaseDialog
        :visible.sync="isShow"
        title="新增"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
        >
        <addModal v-show="isShow" :parentOrgId="parentOrgId" :addParams="addParams" @close="close"/>
        </BaseDialog>
    </div>
</template>

<script>
import {
getChildOrgTreeList,
getChildOrgdetail,
getOrgBrand,
getOrgSeries,
saveOrgInfo,
isSale,
} from '@/api/common/org/companyOrgManage'
import { dictionary } from '@/utils/dictMixin';
import addModal from './addModal'
export default {
name:"Department",
mixins: [dictionary],
components: {
  addModal
},
data() {
      return {
        isSaleArr:[],  
        sanjiao:'sanjiao',
        isDisabled:false,
        isSaveDisabled:false,
        isShow:false,
        isShowSubmit:false,
        isShowFilterTable:false,
        isShowadd:true,
        dataTree: [],
        defaultProps: {
          children: 'children',
          label: 'text'
        },
        formList: this.createFormList(),
        columns: this.createTableColumns(),
        dataSource:[],
        fetchApi: "",
        fetchParams:{},
        params:{
            orgId:0,
            type:10041002,
        },
        BrandData:{
            orgId:0
        },
        SeriesData:{
            orgId:0,
            brandId:''
        },
        OrgInfo:{
            "dataType": 0,
            "isValid": 0,
            "listOBSVO": [],
            "orgCode": "string",
            "orgDesc": "string",
            "orgId": "string",
            "orgName": "string",
            "orgType": 0,
            "parentOrgCode": "string",
            "parentOrgId": "string",
            "parentOrgName": "string",
            "recordVersion": 0
        },
        getDataType:"",
        appId:"",
        addParams:{},
        isTwoLevel:'',
        isFirst:false,
        parentOrgId:"",
        TabHeight: '36.6vh'
      };
    },
    mounted () {
      this.isDisabled=true
      this.getVueTree()
      this.getCookie()
    },
    watch:{
        isShowSubmit(val){
            this.TabHeight = val? '31vh':'36.6vh';
        }
    },
    methods: {
      createFormList() {
        return [
                {
                type: 'INPUT',
                label: '上级组织',
                fieldName: 'parentOrgName',
                orgId:'orgId',
                disabled:true,
                placeholder: '请选择左侧树',
                style: { width: '200px' }
                },{
                type: 'INPUT',
                label: '组织代码',
                fieldName: 'orgCode',
                disabled:true,
                initialValue:"",
                placeholder: '组织代码',
                style: { width: '200px' },
                rules: [{ required: true, message: '请输入组织代码', trigger: 'blur' }]
                },{
                type: 'INPUT',
                label: '组织名称',
                fieldName: 'orgName',
                placeholder: '组织名称',
                style: { width: '200px' },
                rules: [{ required: true, message: '请输入组织名称', trigger: 'blur' }]
                },{
                type: 'SELECT',
                label: '组织类型',
                fieldName: 'orgType',
                disabled:true,
                initialValue:"",
                placeholder: '组织类型',
                itemList:this.createDictList('1506'),
                style: { width: '200px' },
                 rules: [{ required: true, message: '请选择组织类型', trigger: 'change' }]
                },{
                type: 'SELECT',
                label: '组织状态',
                fieldName: 'isValid',
                placeholder: '组织状态',
                itemList:this.createDictList('1001'),
                style: { width: '200px' },
                rules: [{ required: true, message: '请选择组织状态', trigger: 'change' }]
                },{
                type: 'INPUT',
                label: '组织描述',
                fieldName: 'orgDesc',
                placeholder: '组织描述',
                style: { width: '200px' }
                }
            ];
        },

        createTableColumns() {
            return [
                {
                    title: '操作',
                    dataIndex: 'column-action',
                    width: 100,
                    fixed: 'left',
                    hidden:true,
                    render: (props, h) => {
                        return (
                        <div>
                            <el-button size="mini" type="text"  onClick={() => this.deleteHandle(props.row)}>
                             删除
                            </el-button>
                        </div>
                        );
                    }
                },
                {
                    title: '序号',
                    dataIndex: 'index',
                    width: 80,
                    sorter: true,
                    render: props => {
                        return <span>{props.row.index + 1}</span>;
                    }
                },
                {
                    title: '授权类型',
                    dataIndex: 'billType',
                    sorter: true,
                    filterType: 'input',
                    filterItems: [],
                    editable: false,
                    editType: 'select',
                    editItems: this.createDictList('7040')
                },
                {
                    title: '授权品牌',
                    dataIndex: 'brandName',
                    sorter: true,
                    filterType: 'input',
                    filterItems: [],
                    editable: false,
                    editType: 'select',
                    editItems: []
                },
                {
                    title: '授权车系',
                    dataIndex: 'seriesName',
                    sorter: true,
                    filterType: 'input',
                    filterItems: [],
                    editable: false,
                    editType: 'select',
                    editItems: []
                }
            ];
        },
        // getVueTree
        getVueTree(){
            this.dataTree=[]
            getChildOrgTreeList(this.params).then((res)=>{
                this.dataTree.push(res.data[0])
            }).catch(err=>{})
            // 是否销售
            isSale().then(res=>{
                this.isSaleArr = res.data
            })
        },
        getCookie(){
            let allCookie=document.cookie.split(';')
            allCookie.forEach(x=>{
                if(x.indexOf('dataType') > -1 ){
                    this.getDataType=x.split('=')[1]
                }
                if(x.indexOf('appId') > -1 ){
                    this.appId=x.split('=')[1]
                }
            })
            //判断是否为车厂10461003
            // console.log(this.dataType,"dataType")
            /* if(this.dataType == 10461003){
            // console.log(this.dataType,"车厂")
            } */
        },
        //树节点
        handleNodeClick(data) {
            this.isFirst=true
            this.sanjiao=""
            this.formList[0].disabled=true
            this.formList[1].disabled=true
            this.formList[3].disabled=true
            let that=this
            this.isTwoLevel = data.parent
            this.formList[3].itemList=this.createDictList('1506')
            //不要调动顺序
            /* 
            if(data.orgType == "15061009"){
                // 汽车销售
                this.isShowFilterTable=true
                this.isShowadd=false 
                this.isShowSubmit=false
            }else
            */
            // 是否显示table
            this.isSaleArr.map(x=>{
                if(x != data.orgId){
                    this.isShowFilterTable=false
                    this.isShowadd=false
                }
            })
            this.isSaleArr.map(x=>{
                if(x == data.orgId){
                    this.isShowFilterTable=true
                    this.isShowadd=true
                }
            })
            
             if(data.orgType == "15061010" || data.orgType == "15061009"){
                // 汽车售后15061010
                // if(data.orgType == "15061010"){
                //     this.isShowFilterTable=false
                // }else{
                    
                // }
                this.isShowSubmit=false
                // this.isShowadd=false
                this.columns[0].hidden =true
            }else {
                // this.isShowFilterTable=true
                // this.isShowadd=true
                this.isShowSubmit=true
                this.columns[0].hidden =false
            }

            // 不要调动顺序
            if(data.parent == 0 ){
                // this.isShowFilterTable=false
                this.isDisabled=false
                // this.isShowadd=false
                this.isShowSubmit=false
                this.columns[0].hidden =true

                this.formList.find(item =>item.fieldName == "orgName").disabled=true
                this.formList.find(item =>item.fieldName == "isValid").disabled=true
                // this.formList[3].itemList=this.createDictList('1506')
            }else if(data.parent == 14){
                this.isDisabled=false
                this.isShowadd=false
                this.formList.find(item =>item.fieldName == "orgName").disabled=false
                this.formList.find(item =>item.fieldName == "isValid").disabled=false
                // this.formList[3].itemList=this.createDictList('1506')
                if(data.orgType == 15061004 || data.orgType == 15061013){
                    this.isShowSubmit=true
                    this.columns[0].hidden =false
                }
            } else{
                this.formList.find(item =>item.fieldName == "orgName").disabled=false
                this.formList.find(item =>item.fieldName == "isValid").disabled=false
                this.isDisabled=false
            }
            //判断是否是wsl
            /* if(this.appId == 'wsl'){
                if(this.getDataType == "10461001"){
                    if(data.orgType == "15061013" || data.orgType == "15061001" || data.orgType == "15061002" || data.orgType == "15061003" || data.orgType == "15061004" || data.orgType == "15061005" || data.orgType == "15061006" || data.orgType == "15061007" || data.orgType == "15061008" || data.orgType == "15061009" || data.orgType == "15061010" ){
                    this.isSaveDisabled = true
                    console.log(data.orgType,"data.orgType")
                    }else{
                        this.isSaveDisabled = false
                    }
                }
            } */
            console.log(data,"data")
            if(data != "" || data != "undefined"){
                   this.params.orgId=data.orgId
                   this.parentOrgId = data.parentOrgId
                    getChildOrgTreeList(this.params).then((res)=>{
                        data.children=res.data
                    }).catch(err=>{})
                    this.addParams=this.params
                    this.dataSource=[]
                    this.fetchApi=getChildOrgdetail
                    getChildOrgdetail(this.params).then((res)=>{
                        // 保存传递参数
                        that.OrgInfo.dataType=res.data.dataType
                        that.OrgInfo.recordVersion=res.data.recordVersion
                        that.OrgInfo.orgId=res.data.orgId

                        that.OrgInfo.parentOrgId=res.data.parentOrgId
                        that.OrgInfo.parentOrgName=res.data.parentOrgName

                        console.log(res.data.listOBSVO,"res.data.listOBSVO")
                        this.dataSource=res.data.listOBSVO?res.data.listOBSVO:[]
                        that.formList.forEach(x=>{
                            x.initialValue=res.data[x.fieldName];
                            x.orgId=res.data.orgId
                            if(x.fieldName == 'orgType'){
                                x.initialValue = Number(res.data[x.fieldName])
                            }
                        })
                        if(res.data.parentOrgId == null){
                            res.data.parentOrgId=0
                        }

                        // this.getBrandAndSeries(res.data.parentOrgId)
                    }).catch(err=>{})
            }else{
                this.formList.forEach(ele=>{
                    ele.initialValue=""
                })
                this.dataSource=[]
            }
        },

        // 获取品牌/车系
        /* getBrandAndSeries(orgId){
            //品牌
            this.BrandData.orgId=orgId
            this.columns[3].editItems=[]
            this.columns[4].editItems=[]
            getOrgBrand(this.BrandData).then((OrgBrand)=>{
                console.log(OrgBrand,'OrgBrand',this.columns)
                OrgBrand.data.forEach(x=>{
                    this.columns[3].editItems.push({'text':x.brandName,'value':x.brandId})
                })
            }).catch(err=>{})

            // 车系
            this.SeriesData.orgId=orgId
            this.dataSource.forEach(x=>{
                this.SeriesData.brandId=x.seriesId
            })
            getOrgSeries(this.SeriesData).then((res)=>{
                console.log(res,'SeriesData')
                res.data.forEach(x=>{
                    this.columns[4].editItems.push({'text':x.seriesName,'value':`${x.seriesId}`})
                })
            }).catch(err=>{})

        }, */

        //initTableData
        /* initTableData(){
            this.dataSource.forEach(ele=>{
                if(ele.billType == 70401001){
                    ele.seriesId=''
                }else{
                }
            })
        }, */
        //删除
        deleteHandle(row) {
            console.log('取消', row);
            this.$confirm('你确定删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                let rowArr=[]
                rowArr.push(row)
                this.$refs['table'].EXECUTE_DELETE(rowArr)
                this.dataSource.forEach((item,index) => {
                    item.index = index
                })
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                 this.$message({
                    type: 'info',
                    message: '已取消删除'
                });  
            });
        },
        //表格数据变化时
        /* onCellChange(val,val2){
            console.log(val,val2,"val")
            console.log(val[Object.keys(val)[0]],"修改后对应的编码")
            if(val[Object.keys(val)[0]] == val2.brandId){
                this.columns[3].editItems=[]
                this.SeriesData.brandId=val2.brandId
                getOrgSeries(this.SeriesData).then((res)=>{
                    console.log(res,'SeriesData')
                    res.data.forEach(x=>{
                        this.columns[3].editItems.push({'text':x.seriesName,'value':x.seriesId})
                    })
                }).catch(err=>{})
            }
        }, */
        //表格新增
        addHandle(props){
            console.log(props,"props")
            this.isShow=true
        },

        // 新增
        add(){
            let parentOrgName = this.formList[2].initialValue
            console.log(this.formList,"add")
            this.isShowadd=true 
            this.isShowSubmit=true     
            this.SeriesData.orgId=this.formList[0].orgId
            this.OrgInfo.parentOrgId=this.formList[0].orgId
            this.OrgInfo.orgId=''
            this.formList[0].initialValue=parentOrgName
            this.formList[0].disabled=true
            this.formList[1].disabled=false
            // 20191227新增一级可以新建二级
            this.formList.find(item =>item.fieldName == "orgName").disabled=false
            this.formList.find(item =>item.fieldName == "isValid").disabled=false
            this.formList[3].initialValue=15061004
            this.dataSource=[]
            if(this.isTwoLevel == 14){
                this.isShowSubmit=true
                this.columns[0].hidden =false
                
                // this.formList[3].disabled=true
                //this.formList[3].initialValue=15061004
                // this.formList[3].itemList=[{'text': "部门",'value': 15061004},{'text': "销售团队",'value': 15061013}]
            }else{
                // this.formList[3].disabled=false
                // this.formList[3].itemList=[{'text': "部门",'value': 15061004},{'text': "销售团队",'value': 15061013}]
            }
            this.formList[3].itemList=[{'text': "部门",'value': 15061004}]
            this.clearData()
        },
        //保存
        submit(){
            
            let that=this
            let saveData= this.$refs["formPanel"].SUBMIT_FORM()
            console.log(this.formList,this.dataSource,"submit",saveData)

            /* let isCopy=false
            this.dataSource.forEach(x=>{
                if(x != undefined){
                    this.isCopy = true
                }else{
                    this.isCopy = false
                }
            }) 
            if(isCopy){
                this.OrgInfo.listOBSVO=this.dataSource
            }else{
                this.OrgInfo.listOBSVO=[]
            }*/
            this.OrgInfo.listOBSVO=this.dataSource
            this.OrgInfo.parentOrgCode=this.formList[0].orgId
            this.OrgInfo.orgCode=this.formList[1].initialValue
            this.OrgInfo.orgName=this.formList[2].initialValue
            this.OrgInfo.orgType=this.formList[3].initialValue
            this.OrgInfo.isValid=this.formList[4].initialValue
            this.OrgInfo.orgDesc=this.formList[5].initialValue


            console.log(this.OrgInfo,"this.OrgInfo")
            if(this.OrgInfo.parentOrgCode && this.OrgInfo.orgCode &&this.OrgInfo.orgName  &&this.OrgInfo.orgType && this.OrgInfo.isValid){
                     this.isSaveDisabled =true
                    saveOrgInfo(this.OrgInfo).then(res=>{
                    console.log(res,"res")
                    if(res.resultCode  == 200){
                    this.isSaveDisabled =false
                    this.$message({
                            message: `保存成功`,
                            type: 'success'
                        });
                        this.params={
                            orgId:0,
                            type:10041002,
                        }
                        this.getVueTree()
                        this.isFirst=false
                    }else{
                        this.isSaveDisabled =false
                        this.$message({
                            message: `${res.errMsg}`,
                            type: 'success'
                        });
                    }

                    this.params={
                        orgId:0,
                        type:10041002,
                    }
                    // this.clearData()
                    //this.getVueTree(this.params)
                }).catch(err=>{this.isSaveDisabled =false})
            }


        },
        //清空处理
        clearData(){
             this.formList.forEach(ele=>{
                    if(ele.disabled != true){
                        ele.initialValue=""
                    }
                })
        } ,
        //关闭
        close(data){
            this.isShow=false
            
            this.dataSource=_.uniqBy(this.dataSource.concat(data),'brandName')
            console.log(this.dataSource,"this.dataSource")
        },
    }
  };
</script>

<style lang="less" scoped>
.Department{
    .DepartmentBtn{
        padding: 10px;
    }
    .submit{
        width: 100%;
        text-align: center;
        padding: 10px;
    }
    .DepartmentWrap{
        height: 74vh;
        border: 1px solid #000;
        box-sizing: border-box;
        overflow: hidden;
        .leftTree{
            width: 36%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: scroll;
            float: left;
            padding: 10px;
            box-sizing: border-box;
            position: relative;
        }

        .rightContent{
            width: 64%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: scroll;
            float: left;
            box-sizing: border-box;
            padding: 10px;
            border-left: 2px solid #eee;
        }
    }
    .sanjiao{
          position: absolute;
          left: 18px;
          top: 19px;
          z-index: 99;
          width: 0;
          height: 0;
          border-top: 3px solid transparent;
          border-bottom: 5px solid transparent;
          border-left: 9px solid #ccc;
    }
}
</style>
